//
//  Optimal.hpp
//  labuladong
//
//  Created by 刘振舟 on 2024/3/19.
//

#ifndef Optimal_hpp
#define Optimal_hpp
#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

class RandomizedSet {
public:
    vector<int> nums;
    unordered_map<int, int> valueToIndexMap;
    
    RandomizedSet() {
//        初始化 rand() 函数的随机数种子。
        srand((unsigned)time(NULL));
    }
    
    bool insert(int val) {
        if (!valueToIndexMap.count(val)) {
            return false;
        }
        valueToIndexMap[val] = nums.size();
        nums.push_back(val);
        return true;
    }
    
    bool remove(int val) {
        if (!valueToIndexMap.count(val)) {
            return false;
        }
        int index = valueToIndexMap[val];
        valueToIndexMap[nums.back()] = index;
        swap(nums.back(), nums[index]);
        nums.pop_back();
        valueToIndexMap.erase(val);
        return true;
    }
    
    int getRandom() {
        int index = rand() % nums.size();
        return nums[index];
    }
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet* obj = new RandomizedSet();
 * bool param_1 = obj->insert(val);
 * bool param_2 = obj->remove(val);
 * int param_3 = obj->getRandom();
 */

#endif /* Optimal_hpp */
